import requests
import json
from logging_config import get_device_logger

logger = get_device_logger("jd_task")


class JDCrawler:
    """
    京东客户数据爬虫类
    接口地址: https://jd.35125.com/erp/Customer/cusLunhuList
    """

    def __init__(self, cookies):
        self.url = "https://jd.35125.com/erp/Customer/cusLunhuList"
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        if  cookies:
            self.headers['Cookie'] = cookies

    def build_customers(self,  jd_data):
        customers = []
        if  not jd_data.get("data") or not jd_data["data"].get("list"):
            return []
        for customer in jd_data["data"]["list"]:
            customer_data = {
                "customer_name": customer["CNAME"],
                "phone": customer["tel"],
                "customer_situation": customer["ASSETS"]
            }
            customers.append(customer_data)

        logger.info(f"获取到{len(customers)}个客户数据")
        return customers

    def crawl_customer_data(self, page=1, limit=10, state=7, type=5):
        """
        爬取客户数据

        Args:
            page (int): 页码
            limit (int): 每页数量
            state (int): 状态
            type (int): 类型

        Returns:
            dict: 返回的JSON数据，如果失败返回None
        """
        # 请求参数
        data = {
            'page': page,
            'limit': limit,
            'state': state,
            'type': type
        }

        try:
            # 发送POST请求
            response = requests.post(self.url, data=data, headers=self.headers)

            # 检查响应状态码
            if response.status_code == 200:
                # 解析JSON响应
                result = response.json()
                logger.info("轮呼请求成功，返回数据:")
                # logger.info(json.dumps(result, indent=2, ensure_ascii=False))
                return result
            else:
                logger.error(f"请求失败，状态码: {response.status_code}")
                logger.error(f"响应内容: {response.text}")
                return None

        except requests.exceptions.RequestException as e:
            logger.exception(f"请求发生错误: {e}")
            return None
        except json.JSONDecodeError as e:
            logger.exception(f"JSON解析错误: {e}")
            logger.error(f"响应内容: {response.text}")
            return None

    def get_customers(self):
        """
        获取客户数据
        """
        jd_data = self.crawl_customer_data()
        return self.build_customers(jd_data)

    def crawl_staff_data(self):
        staff_url = "https://jd.35125.com/erp/Staff/getStaffRow"
        try:
            # 发送POST请求，无参数
            response = requests.post(staff_url, headers=self.headers)
            # 检查响应状态码
            if response.status_code == 200:
                # 解析JSON响应
                result = response.json()
                logger.info(f"[用户数据]获取成功tel:{result.get('data').get('ULOGIN')}")
                return result
            else:
                logger.error(f"[用户数据]请求失败，状态码: {response.status_code}")
                logger.error(f"响应内容: {response.text}")
                return None

        except requests.exceptions.RequestException as e:
            logger.exception(f"员工数据请求发生错误: {e}")
            return None
        except json.JSONDecodeError as e:
            logger.exception(f"员工数据JSON解析错误: {e}")
            logger.error(f"响应内容: {response.text}")
            return None

    def clear_all_lunhu_tasks(self):
        clear_url = "https://jd.35125.com/erp/Customer/delAlllunhu"

        try:
            # 发送POST请求，无参数
            response = requests.post(clear_url, headers=self.headers)

            # 检查响应状态码
            if response.status_code == 200:
                # 解析JSON响应
                result = response.json()
                logger.info("清除所有轮呼任务请求成功，返回数据:")
                logger.info(json.dumps(result, indent=2, ensure_ascii=False))
                return result
            else:
                logger.error(f"清除所有轮呼任务请求失败，状态码: {response.status_code}")
                logger.error(f"响应内容: {response.text}")
                return None

        except requests.exceptions.RequestException as e:
            logger.exception(f"清除所有轮呼任务请求发生错误: {e}")
            return None
        except json.JSONDecodeError as e:
            logger.exception(f"清除所有轮呼任务JSON解析错误: {e}")
            logger.error(f"响应内容: {response.text}")
            return None


# # 保持向后兼容的函数接口
# def crawl_customer_data():
#     """
#     爬取客户数据 (向后兼容的函数)
#     """
#     crawler = JDCrawler()
#     return crawler.crawl_customer_data()


if __name__ == '__main__':
    cookies = "PHPSESSID=4dknpgjncakem0sskt7vd8vumm;"
    crawler = JDCrawler(cookies=cookies)
    crawler.crawl_customer_data()
